package load

import (
	"log"
	"math/rand"
	"os"
)

/**
 * @Author：落叶知秋
 * @Date：15:21 2022/6/16
 * @note：
 **/

func GetMove(ch chan<- string) {
	for {
		intput, err := ReadInput()
		if err != nil {
			log.Println("error reading input:", err)
			ch <- "ESC"
		}
		ch <- intput
	}
}

// ReadInput 使用os.stdin.read进行读取
func ReadInput() (st string, err error) {
	buffer := make([]byte, 100)
	//读取，数据，返回字节数
	cnt, err := os.Stdin.Read(buffer)
	if err != nil {
		return "", err
	}
	//如果只读取了衣蛾字节，或者读取的字节是。。。,判断停止
	if cnt == 1 && buffer[0] == 0x1b { //获取的是esc按钮的阿斯克码
		return "ESC", nil
	} else if cnt >= 3 {
		if buffer[0] == 0x1b && buffer[1] == '[' {
			switch buffer[2] {
			case 'A':
				return "UP", nil
			case 'B':
				return "DOWN", nil
			case 'C':
				return "RIGHT", nil
			case 'D':
				return "LEFT", nil
			}
		}
	}
	return
}

func drawDirection() string {
	dir := rand.Intn(4)
	move := map[int]string{
		0: "UP",
		1: "DOWN",
		2: "RIGHT",
		3: "LEFT",
	}
	return move[dir]
}
